package db

import (
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

func Paginate(r *http.Request) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		query := r.URL.Query()

		page, _ := strconv.Atoi(query.Get("current"))
		if page == 0 {
			page = 1
		}
		pageSize, _ := strconv.Atoi(query.Get("pageSize"))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

type TunnelList []Tunnel

func (list *TunnelList) ListByEnabled(db *gorm.DB) {
	db.Find(list, "enabled = ?", true)
}

type LocalServerList []*LocalServer

func (list *LocalServerList) ListByEnabled(db *gorm.DB) {
	db.Find(list, "enabled = ?", true)
}

type SshServerList []*SshServer

func (list *SshServerList) ListByEnabled(db *gorm.DB) {
	db.Find(list, "enabled = ?", true)
}

type RouteRuleList []*RouteRule

func (list *RouteRuleList) ListByEnabled(db *gorm.DB) {
	db.Find(list, "enabled = ?", true)
}

type ProxyList []Proxy

func (list *ProxyList) ListByEnabled(db *gorm.DB) {
	db.Find(list, "enabled = ?", true)
}

type TcpForwardList []TcpForward

func (list *TcpForwardList) ListByEnabled(db *gorm.DB) {
	db.Find(list, "enabled = ?", true)
}
